package cn.zhangxin.pethome.system.fastdf;

import cn.zhangxin.pethome.utils.AjaxResult;
import cn.zhangxin.pethome.utils.FastdfsUtil;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fast")
@Api(value = "文件的API",description="文件上传下载功能")
public class FastdfController {
    //上传
    /**
     * RequestPart:
     * required = true请求参数认证 必须传参数
     * value：名字必须为file
     * http://123.207.27.208//group1/M00/03/6A/CgAIC2O5pC6AdGGuAAJ1a40aDR8626.jpg
     * */
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file) throws IOException {
        try {
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();//获得上传文件名字，全名包含后缀名
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);//获得后缀包含点
            String uploadPath = FastdfsUtil.upload(bytes, suffix);//返回路径 包含组
            return AjaxResult.success().setData(uploadPath);//给前端返回保存路径
        }catch (IOException e){
            return AjaxResult.error().setMsg("上传失败，请联系管理员");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请稍后再试");
        }

    }
    //下载

    //删除
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path") String  path) throws IOException {
        //System.out.println(path);
        try {
            String filePath = path.substring(1);//去掉传进来的第一个斜杠
            String groupName = filePath.substring(0, filePath.indexOf("/"));//获得组
            String fileName = filePath.substring(filePath.indexOf("/")+1);//获得路径
            System.out.println(groupName);
            System.out.println(fileName);
            FastdfsUtil.delete(groupName,fileName);
            return AjaxResult.success().setMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg("网络异常，请稍后再试");
        }
    }
}
